<template>
  <div class="regist-container">
    <el-form
      ref="registForm"
      :model="registForm"
      class="regist-form"
      auto-complete="on"
      label-position="left"
      :rules="registRules"
    >
      <div class="title-container">
        <h3 class="title">注册</h3>
      </div>

      <el-form-item prop="username">
        <el-input
          ref="username"
          v-model="registForm.username"
          placeholder="用户名"
          name="username"
          type="text"
          tabindex="1"
          auto-complete="on"
        />
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          :key="passwordType"
          ref="password"
          v-model="registForm.password"
          :type="passwordType"
          placeholder="密码"
          name="password"
          tabindex="2"
          auto-complete="on"
          @keyup.enter.native="handleLogin"
        />
        <span class="show-pwd" @click="showPwd">
          <svg-icon
            :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'"
          />
        </span>
      </el-form-item>
      <el-form-item prop="name">
        <el-input v-model="registForm.name" placeholder="姓名"></el-input>
      </el-form-item>
      <el-form-item prop="telephone">
        <el-input v-model="registForm.telephone" placeholder="手机号">
        </el-input>
      </el-form-item>
      <el-form-item prop="email">
        <el-input v-model="registForm.email" placeholder="邮箱">
          <el-button
            type="text"
            :disabled="registForm.email == ''"
            class="btn"
            slot="append"
            @click="getCode()"
            >{{ isRun ? `验证码(${runTime}s)` : `获取验证码` }}</el-button
          >
        </el-input>
      </el-form-item>
      <el-form-item prop="code">
        <el-input v-model="registForm.code" placeholder="验证码"></el-input>
      </el-form-item>
      <el-button
        :loading="loading"
        type="primary"
        style="width: 100%; margin-bottom: 30px"
        @click.native.prevent="handleRegist"
        >注册</el-button
      >
    </el-form>
  </div>
</template>

<script>
import { validUsername } from "@/utils/validate";
import { registWithoutAuth, getCode, signUp } from "@/api/user";

export default {
  name: "regist",
  data() {
    // 自定义邮箱校验
    const validateEmail = (rule, value) => {
      let emailReg =
        /^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,5}$/;
      if (!value) {
        return Promise.reject("邮箱不能为空");
      } else if (!emailReg.test(value)) {
        return Promise.reject("邮箱格式不正确");
      } else {
        return Promise.resolve();
      }
    };
    // 自定义手机号校验
    const validPhone = (rule, value) => {
      let phoneReg =
        /^1(3\d|4[5-9]|5[0-35-9]|6[567]|7[0-8]|8\d|9[0-35-9])\d{8}$/;
      if (!value) {
        return Promise.reject("手机号不能为空");
      }
      if (!phoneReg.test(value)) {
        return Promise.reject("手机号格式不正确");
      } else {
        return Promise.resolve();
      }
    };
    const validateUsername = (rule, value, callback) => {
      if (value.length <= 3 || value.length > 18) {
        callback(new Error("请输入正确的用户名"));
      } else {
        callback();
      }
    };
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error("密码不能少于6位"));
      } else {
        callback();
      }
    };
    return {
      registForm: {
        code: "",
        email: "",
        name: "",
        password: "",
        telephone: "",
        username: "",
      },
      registRules: {
        username: [
          { required: true, trigger: "blur", validator: validateUsername },
        ],
        password: [
          { required: true, trigger: "blur", validator: validatePassword },
        ],
        code: [{ required: true, trigger: "blur", message: "请输入验证码" }],
        telephone: [{ required: true, validator: validPhone }],
        email: [{ required: true, validator: validateEmail }],
        name: [{ required: true, trigger: "blur", message: "请输入姓名" }],
      },
      loading: false,
      passwordType: "password",
      redirect: undefined,
      open: false,
      form: {
        username: undefined,
        code: undefined,
      },
      isRun: false,
      runTime: 300,
    };
  },
  watch: {
    $route: {
      handler: function (route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true,
    },
  },
  methods: {
    // 注册
    async handleRegist() {
      this.$refs.registForm.validate(async (valid) => {
        if (valid) {
          let res = await signUp(this.registForm);
          console.log(res);
          if (res.code == 200) {
            this.$message.success(res.data);
            this.$router.push({ path: "/login" });
          }
        }
      });
    },
    getCode() {
      if (this.isRun) return; //如果开始倒计时
      this.isRun = true;
      this.autoTimer = setInterval(() => {
        if (this.runTime === 0) {
          this.runTime = 300;
          this.isRun = false;
          // 清除定时器
          clearInterval(this.autoTimer);
          return;
        }
        this.runTime--;
      }, 1000);
      if (this.runTime === 300) {
        getCode({ address: this.registForm.email }).then((res) => {
          if (res.code == 200) {
            console.log(res);
          }
        });
      }
    },
    showPwd() {
      if (this.passwordType === "password") {
        this.passwordType = "";
      } else {
        this.passwordType = "password";
      }
      this.$nextTick(() => {
        this.$refs.password.focus();
      });
    },
    // handleregist() {
    //     this.$refs.registForm.validate((valid) => {
    //         if (valid) {
    //             this.loading = true;
    //             this.$store
    //                 .dispatch("user/regist", this.registForm)
    //                 .then(() => {
    //                     this.$router.push({ path: this.redirect || "/" });
    //                     this.loading = false;
    //                     this.$message.success('登录成功')
    //                 })
    //                 .catch((err) => {
    //                     this.loading = false;
    //                     this.$message.error('账号或者密码错误')
    //                 });
    //         } else {
    //             console.log("error submit!!");
    //             return false;
    //         }
    //     });
    // },
  },
};
</script>

<style lang="scss">
/* 修复input 背景不协调 和光标变色 */
/* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */

$bg: #283443;
$light_gray: #fff;
$cursor: #fff;

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .regist-container .el-input input {
    color: $cursor;
  }
}

/* reset element-ui css */
.regist-container {
  .el-input {
    // display: inline-block;
    height: 47px;
    // width: 85%;

    input {
      background: transparent;
      border: 0px;
      -webkit-appearance: none;
      border-radius: 0px;
      padding: 12px 5px 12px 15px;
      color: $light_gray;
      height: 47px;
      caret-color: $cursor;

      &:-webkit-autofill {
        box-shadow: 0 0 0px 1000px $bg inset !important;
        -webkit-text-fill-color: $cursor !important;
      }
    }
    .el-input-group__append,
    .el-input-group__prepend {
      background: #283443;
      border: none;
      border-color: transparent;
    }
    .btn {
      margin-right: 5px;
    }
  }

  .el-form-item {
    border: 1px solid rgba(255, 255, 255, 0.1);
    background: rgba(0, 0, 0, 0.1);
    border-radius: 5px;
    color: #454545;
  }
}
</style>

<style lang="scss" scoped>
$bg: #2d3a4b;
$dark_gray: #889aa4;
$light_gray: #eee;

.regist-container {
  min-height: 100%;
  width: 100%;
  background-color: $bg;
  overflow: hidden;

  .regist-form {
    position: relative;
    width: 520px;
    max-width: 100%;
    padding: 160px 35px 0;
    margin: 0 auto;
    overflow: hidden;
  }

  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;

    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }

  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }

  .title-container {
    position: relative;

    .title {
      font-size: 26px;
      color: $light_gray;
      margin: 0px auto 40px auto;
      text-align: center;
      font-weight: bold;
    }
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }
}
</style>
